package LeetCode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName interview
 * @Description: TODO
 * @date ${DAT}17:33
 */
public class LeetCode216 {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        if (k == 0 || n == 0){
            return res;
        }
        List<Integer> list = new ArrayList<>();
        dfs(k,n,1,list,0);
        return res;
    }

    public void dfs(int k, int n, int begin, List<Integer> list,int index){
        if (index == k && n == 0){
            res.add(new ArrayList<>(list));
            return;
        }
        if (index == k){
            return;
        }
        for (int i = begin; i <= 9; i++){
            if (i > n){
                continue;
            }
            list.add(i);
            dfs(k,n - i,i + 1,list,index + 1);
            list.remove(list.size() - 1);
        }
    }

    public static void main(String[] args) {
        System.out.println(new LeetCode216().combinationSum31(3, 7).toString());
    }

    public List<List<Integer>> combinationSum31(int k, int n) {
        if (k == 0 || n == 0){
            return res;
        }
        List<Integer> list = new ArrayList<>();
        dfs2(k,n,1,list,0);
        return res;
    }
    public void dfs2(int k, int n, int begin, List<Integer> list,int index){
        if (index == k && n == 0){
            res.add(new ArrayList<>(list));
            return;
        }
        if (index == k){
            return;
        }
        for (int i = begin; i <= 9; i++){
            if (n < i){
                break;
            }
            list.add(i);
            dfs2(k,n - i,i + 1,list,index + 1);
            list.remove(list.size() - 1);
        }
    }
}
